package com.gexiaobao.pigeon.ui.fragment.mine.organization.activity

import android.annotation.SuppressLint
import android.graphics.Paint
import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.ext.RxTextTool
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.model.bean.VisitPersonResponse
import com.gexiaobao.pigeon.app.model.bean.VisitReservationResponse
import com.gexiaobao.pigeon.app.util.ImageLoaderManager
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.databinding.ActivityVisitByAppointmentBinding
import com.gexiaobao.pigeon.ui.adapter.AdapterVisitPerson
import com.gexiaobao.pigeon.ui.adapter.ProofPictureAdapter
import com.gexiaobao.pigeon.ui.adapter.VisitReservationAdapter
import com.gexiaobao.pigeon.viewmodel.OrgDetailViewModel
import com.google.gson.Gson
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.startActivity
import me.hgj.jetpackmvvm.util.startActivityForResult
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody


/**
 * @Author      : hxw
 * @Date        : 2024/5/31 14:32
 * @Describe    : 预约探视
 */
class ActivityVisitByAppointment : BaseActivity<OrgDetailViewModel, ActivityVisitByAppointmentBinding>() {

    private var mLodgingIs = false
    private var mLodgingNum = 0
    private val mAdapterPerson: AdapterVisitPerson by lazy { AdapterVisitPerson(arrayListOf()) }
    private val mAdapter: VisitReservationAdapter by lazy { VisitReservationAdapter(arrayListOf()) }
    private val mProofAdapter: ProofPictureAdapter by lazy { ProofPictureAdapter(arrayListOf()) }
    private var mMemberId = 0
    private var mRaceId = 0
    private var mState = 0//审核状态1-审核中  2-审核通过  3-审核驳回
    private var endStatus = false//1-，2-
    private var mReserveType = 0//探视类型
    private var mOrderId = 0
    private var mOrgIcon = ""
    private val dataImageList: MutableList<String> = arrayListOf()

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        mDatabind.includeBtn.tvLeftBtn.text = getString(R.string.commit_yuding)
        mDatabind.includeBtn.tvRightBtn.text = getString(R.string.Upload_credentials)
        mDatabind.includeOrgTitle.llAllVisitInfo.isVisible = true

        mDatabind.includeOrgTitle.tvAllAppointmentInfo.paint.flags = Paint.UNDERLINE_TEXT_FLAG//设置下划线
        mDatabind.includeOrgTitle.tvVisitAnnouncement.paint.flags = Paint.UNDERLINE_TEXT_FLAG

        mRaceId = intent.getIntExtra("raceId", 0)
        mMemberId = intent.getIntExtra("memberId", 0)
        mDatabind.recyclerViewVisit.init(LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false), mAdapter)
        mDatabind.recyclerViewVisit.adapter = mAdapter

        mDatabind.swipeRecyclerViewStay.init(GridLayoutManager(this, 5), mAdapterPerson)

        mDatabind.recyclerViewPicProof.layoutManager = GridLayoutManager(this, 3)
        mDatabind.recyclerViewPicProof.adapter = mProofAdapter

        onRefresh()

        mDatabind.swipeRefreshLayout.init {
            onRefresh()
        }

        mDatabind.rbSceneVisit.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                mReserveType = 1
            }
        }
        mDatabind.rbVideoVisit.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                mReserveType = 2
            }
        }
        mDatabind.rbNoVisit.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                mReserveType = 3
            }
        }

        mProofAdapter.setOnItemClickListener { _, _, position ->
            openAdapterBigImage(position, mDatabind.recyclerViewPicProof, dataImageList)
        }

        mAdapterPerson.setOnItemPersonPassedListener(object : AdapterVisitPerson.OnItemClickPersonListener {
            override fun onItemPersonVisit(personNum: Int) {
                mLodgingNum = personNum
            }
        })

        mDatabind.radioWaive.setOnCheckedChangeListener { _, b ->
            if (b) {
                mLodgingIs = false
                mLodgingNum = 0
                mDatabind.swipeRecyclerViewStay.isVisible = false
            }
        }
        mDatabind.radioOrder.setOnCheckedChangeListener { _, b ->
            if (b) {
                mLodgingIs = true
                if (mAdapterPerson.data.isNotEmpty()) {
                    val isVisit = arrayListOf<Boolean>()
                    mAdapterPerson.data.forEach {
                        if (it.isSelected) {
                            isVisit.add(true)
                        }
                    }
                    if (!isVisit.contains(true)) {
                        mAdapterPerson.data[0].isSelected = true
                        mAdapterPerson.setSelectedPosition(0)
                        mAdapterPerson.notifyItemChanged(0)
                        mLodgingNum = 1
                    }
                }
                mDatabind.swipeRecyclerViewStay.isVisible = true
            }
        }
    }

    private fun getVisitPersonList(num: Int): ArrayList<VisitPersonResponse> {
        val data = arrayListOf<VisitPersonResponse>()
        for (i in 1..num) {
            data.add(VisitPersonResponse((i.toString() + "人"), false))
        }
        return data
    }

    private fun onRefresh() {
        showLoading(getString(R.string.loading))
//        mViewModel.getVisitInfo(mRaceId, mMemberId)//接口串行请求案例
        mViewModel.getLoftPigeonListByMemberId(mRaceId, mMemberId)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun createObserver() {
        super.createObserver()
        /** 新增预约探视 */
        mViewModel.addVisitResult.observe(this) {
            dismissLoading()
            finish()
        }

        /** 获取探视预定详情 */
        mViewModel.visitResult.observe(this) {
            if (mDatabind.swipeRefreshLayout.isRefreshing) {
                mDatabind.swipeRefreshLayout.isRefreshing = false
            }
            if (it != null) {
                refreshData(it)
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun refreshData(it: VisitReservationResponse) {
        mOrderId = it.id
        mOrgIcon = it.icon
        mLodgingNum = it.lodgingNum
        mLodgingIs = it.lodgingIs
        val siteVisit = it.siteVisitions
        val videoVisit = it.videoVisitions
        val noVisit = it.notVisitions
        mDatabind.rbSceneVisit.isVisible = siteVisit == 1
        mDatabind.rbVideoVisit.isVisible = videoVisit == 1
        mDatabind.rbNoVisit.isVisible = noVisit == 1
        mDatabind.llVisitPerson.isVisible = it.lodgingState
        mDatabind.swipeRecyclerViewStay.isVisible = mLodgingIs
        mDatabind.radioWaive.isChecked = !mLodgingIs
        mDatabind.radioOrder.isChecked = mLodgingIs

        mDatabind.visitTypeClosed.isVisible = siteVisit == 2 && videoVisit == 2 && noVisit == 2
        mDatabind.radioGroupVisit.isVisible = siteVisit == 1 || videoVisit == 1 || noVisit == 1
        mDatabind.llProofPicture.isVisible = it.voucher.isNotEmpty()
        ImageLoaderManager.loadCircleImageFall(this, it.icon, mDatabind.includeOrgTitle.ivOrgIcon, R.mipmap.profilepic_str_1)
        mDatabind.includeOrgTitle.tvIncludeOrgName.text = it.orgName
        mDatabind.includeOrgTitle.tvIncludeOrgRaceName.text = it.raceName
        RxTextTool.getBuilder("").append(getString(R.string.payment_amount) + ": ").append(it.unpaidAmount.toString())
            .setTextColor(ContextCompat.getColor(this, R.color.color_f65a5a)).setAppearance(60).append(getString(R.string.yuan))
            .into(mDatabind.tvVisitPayMoney)
        RxTextTool.getBuilder("").append(getString(R.string.Reservation_size) + ": ").append(it.allTotal.toString())
            .setTextColor(ContextCompat.getColor(this, R.color.color_f65a5a)).setAppearance(60).append(getString(R.string.yu))
            .into(mDatabind.tvVisitPigeonNo)
        mAdapter.setList(it.list)
        mAdapter.notifyDataSetChanged()

        mProofAdapter.setList(it.voucher)
        mProofAdapter.notifyDataSetChanged()
        if (it.lodgingNumMax > 0) {
            mAdapterPerson.setList(getVisitPersonList(it.lodgingNumMax))
            if (it.lodgingNum > 0) {
                mAdapterPerson.setSelectedPosition(it.lodgingNum - 1)
                mAdapterPerson.data[it.lodgingNum - 1].isSelected = true
            } else {
                mAdapterPerson.setSelectedPosition(0)
                mAdapterPerson.data[0].isSelected = true
            }
            mAdapterPerson.notifyDataSetChanged()
        }

        mDatabind.includeBtn.tvRightBtn.isVisible = it.state == 1 && it.voucherState//右边按钮文案【上传凭证】当状态是1并且缴费凭证开启时 才显示

        dataImageList.clear()
        dataImageList.addAll(it.voucher)

        mReserveType = it.visitType
        when (mReserveType) {
            1 -> mDatabind.rbSceneVisit.isChecked = true
            2 -> mDatabind.rbVideoVisit.isChecked = true
            else -> mDatabind.rbNoVisit.isChecked = true
        }
        endStatus = it.endStatus//如果为true，代表预约通道已关闭
        mState = it.state
        when (mState) {
            0 -> {
                mDatabind.includeBtn.llBottomBtn.isVisible = true//底部按钮显示
                mDatabind.includeBtn.tvLeftBtn.text = getString(R.string.commit_yuding)//提交预定
                mDatabind.tvVisitState.text = getString(R.string.Visit_by_appointment)//预约探视
            }

            1 -> {//审核中
                mDatabind.includeBtn.llBottomBtn.isVisible = true//底部按钮显示
                mDatabind.tvVisitState.text = getString(R.string.have_already_reserved)//已预约，等待审核
                mDatabind.includeBtn.tvLeftBtn.text = getString(R.string.Resubmit_reservation)//重新提交预定
                mDatabind.ivVisitState.background = ContextCompat.getDrawable(this, R.mipmap.icon_under_review)
            }

            2 -> {//审核通过
                mDatabind.includeBtn.llBottomBtn.isVisible = false//底部按钮都隐藏
                mDatabind.tvVisitState.text = getString(R.string.book_successfully)//预约成功
                mDatabind.ivVisitState.background = ContextCompat.getDrawable(this, R.mipmap.icon_reservation_successful)
            }

            else -> {
                mDatabind.includeBtn.llBottomBtn.isVisible = true
                mDatabind.includeBtn.tvLeftBtn.text = getString(R.string.commit_yuding)//提交预定
                mDatabind.tvVisitState.text = getString(R.string.Failure_Audit)//审核失败，请重新提交
                mDatabind.ivVisitState.background = ContextCompat.getDrawable(this, R.mipmap.icon_appointmenr_rejection)
            }
        }

        if (mState == 1 || mState == 3) {
            if (it.changeState == 1) {//1-可更改,2-不可更改
                changeUiState(true)
            } else {
                changeUiState(false)
            }
        } else if (mState == 2) {
            changeUiState(false)
        } else {
            changeUiState(true)
        }

        if (mState == 2) {
            changeStateLodging(false)
        } else {
            changeStateLodging(true)
        }
    }

    private fun changeStateLodging(b: Boolean) {
        mDatabind.radioWaive.isClickable = b
        mDatabind.radioOrder.isClickable = b
        mAdapterPerson.isItemClickable = b
    }

    private fun changeUiState(b: Boolean) {
        mDatabind.rbNoVisit.isClickable = b
        mDatabind.rbSceneVisit.isClickable = b
        mDatabind.rbVideoVisit.isClickable = b
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.includeBtn.tvLeftBtn, mDatabind.includeBtn.tvRightBtn, mDatabind.includeOrgTitle.ivOrgIcon,
            mDatabind.includeOrgTitle.tvAllAppointmentInfo, mDatabind.includeOrgTitle.tvVisitAnnouncement,
            mDatabind.ivVisitBack
        ) { it ->
            when (it) {
                mDatabind.ivVisitBack -> finish()
                mDatabind.includeOrgTitle.tvVisitAnnouncement -> startActivity<ActivityVisitAnnouncement>("raceId" to mRaceId)
                mDatabind.includeOrgTitle.tvAllAppointmentInfo -> startActivity<ActivityAllAppointmentInfo>("raceId" to mRaceId)
                mDatabind.includeOrgTitle.ivOrgIcon -> openBigImage(mDatabind.includeOrgTitle.ivOrgIcon, mOrgIcon)
                mDatabind.includeBtn.tvLeftBtn -> submitVisit()
                mDatabind.includeBtn.tvRightBtn -> {
                    startActivityForResult<ActivitySubmitProof>("id" to mOrderId, "activity" to "ActivityVisitByAppointment") {
                        if (it != null && it.getBooleanExtra("isRefresh", false)) {
                            onRefresh()
                        }
                    }
                }
            }
        }
    }

    private fun submitVisit() {
        if (endStatus) {
            RxToast.warning(getString(R.string.visiting_appointment_over))
            return
        }
        if (mAdapter.data.size == 0) {
            RxToast.warning(getString(R.string.no_visitation))
            return
        }
        showLoading(getString(R.string.loading))
        if (mState == 0) {//新增//修改和重新提交
            val map = mapOf(
                "raceId" to mRaceId,
                "visitType" to mReserveType,
                "memberId" to mMemberId,
                "lodgingNum" to mLodgingNum,
                "lodgingIs" to mLodgingIs
            )
            val body: RequestBody = Gson().toJson(map).toRequestBody("application/json".toMediaTypeOrNull())
            mViewModel.addVisitReservation(body)
        } else {
            val map = mapOf(
                "id" to mOrderId,
                "visitType" to mReserveType,
                "lodgingNum" to mLodgingNum,
                "lodgingIs" to mLodgingIs
            )
            val body: RequestBody = Gson().toJson(map).toRequestBody("application/json".toMediaTypeOrNull())
            mViewModel.editVisitReservationInfo(body)
        }
    }

}